package com.tiancai.service.Impl;

import com.tiancai.context.BaseContext;
import com.tiancai.enums.PayStatus;
import com.tiancai.enums.PayType;
import com.tiancai.mapper.UserMapper;
import com.tiancai.mapper.WorkMapper;
import com.tiancai.pojo.dto.OrderDto;
import com.tiancai.pojo.po.Orders;
import com.tiancai.mapper.OrderMapper;
import com.tiancai.pojo.po.User;
import com.tiancai.pojo.po.Work;
import com.tiancai.pojo.vo.OrderVo;
import com.tiancai.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tiancai
 * @since 2025-03-17
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements IOrderService {

    @Autowired
    private  OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkMapper workMapper;
    @Override
    public Orders add(OrderDto orderDto) {
        Work work = workMapper.selectById(orderDto.getProductId());
        // User user = userMapper.selectById(work.getUserId());
        //根据时间戳生成订单编号，只需要code编号;
        String code = String.valueOf(System.currentTimeMillis());

        Orders orders = Orders.builder()
                .code(code)
                .type(orderDto.getType())
                .currency(orderDto.getCurrency())
                .customerId(BaseContext.getCurrentId())
                .sellerId(work.getUserId())
                .productId(orderDto.getProductId())
                .payMethod(orderDto.getPayMethod())
                .payStatus(PayStatus.PAY)
                .build();
        //查看是否是租赁
        if (orderDto.getType() == PayType.RENT){
            //租赁价格
            orders.setPrice(work.getRentPrice());
        }else {
            //购买价格
            orders.setPrice(work.getPrice());
        }
        orderMapper.insert(orders);
        return orders;
    }

    @Override
    public OrderVo getOrderById(Long id) {
        Orders orders = orderMapper.selectById(id);
        //查看卖家名字
        User user = userMapper.selectById(orders.getSellerId());
        //查看作品名称
        Work work = workMapper.selectById(orders.getProductId());
        OrderVo orderVo = OrderVo.builder()
                .code(orders.getCode())
                .type(orders.getType())
                .createTime(orders.getCreateTime())
                .currency(orders.getCurrency())
                .sellerName(user.getUsername())
                .workName(work.getTitle())
                .payMethod(orders.getPayMethod())
                .payStatus(orders.getPayStatus())
                .build();
        return orderVo;
    }
}
